package com.graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution785 {
    int[] father;

    public boolean isBipartite(int[][] graph) {
        father = new int[graph.length];
        for (int i = 0; i < graph.length; i++) {
            father[i] = i;
        }
        for (int i = 0; i < graph.length; i++) {
            int[] edge = graph[i];
            for (int x : edge) {
                if (same(i, x)) return false;
                join(edge[0], x);
            }
        }
        return true;
    }

    public int find(int x) {
        if (x == father[x]) return x;
        father[x] = find(father[x]);
        return father[x];
    }

    public boolean same(int x, int y) {
        x = find(x);
        y = find(y);
        return x == y;
    }

    public void join(int x, int y) {
        x = find(x);
        y = find(y);
        if (x == y) return;
        father[y] = x;
    }
}
